/**
 * SysRoleAction.java
 * Created at 2017-2-7
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.system.model.SysRole;
import com.broadtext.rms.system.model.SysUserRole;
import com.broadtext.rms.system.service.ISysResourceService;
import com.broadtext.rms.system.service.ISysRoleService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: SysRoleAction
 * </p>
 * <p>
 * Description: 角色管理页面交互类
 * </p>
 * <p>
 * Author: shihui
 * </p>
 * <p>
 * Date: 2017-2-7
 * </p>
 */
@Controller
@RequestMapping("/main/sysRole")
public class SysRoleAction {
    /**
     * sysDictService
     */
    @Autowired
    @Qualifier("sysRoleService")
    private ISysRoleService sysRoleService;
    
    /**
     * sysResourceService 
     */
    @Autowired
    @Qualifier("sysResourceService")
    private ISysResourceService sysResourceService;

    /**
     * 
     * <p>
     * Description: 查询角色列表
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("/getRole.mvc")
    @ResponseBody
    public void getRole(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<SysRole> pageBean;
            pageBean = this.sysRoleService.findEntityPageByQuery(map, pageBounds);
            Map dataMap;
            dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * <p>Description: 角色管理页面：查询角色数据用于角色树列</p>
     * @param request 请求
     * @param response 响应
     * @return 角色
     */
    @RequestMapping(value = "/getRolesTree.mvc")
    @ResponseBody
    public Map<String, Object> getResourceTree(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        List<SysRole> list;
        list = new ArrayList<SysRole>();
        try {
            list = this.sysRoleService.getRolesTree();
        } catch (DaoException e) {
            e.printStackTrace();
        }
        dataMap.put("aaData", list);
        return dataMap;
    }

    /**
     * 
     * <p>Description: 查询角色下的用户</p>
     * @param request 请求
     * @param response 响应
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/getRoleUser.mvc")
    @ResponseBody
    public void getRoleUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        String aoData;
        aoData = request.getParameter("aoData");
        JSONArray array;
        array = JSON.parseArray(aoData);
        map = new HashMap<String, Object>();
        if (array != null) {
            Iterator it;
            it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<Object> pageBean;
            pageBean = this.sysRoleService.findUserByRole(map, pageBounds);
            Map dataMap;
            dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>Description: 查询角色基础信息</p>
     * @param request 请求
     * @param response 响应
     * @return 查询结果
     */
    @RequestMapping(value = "/getRoleInfo.mvc")
    @ResponseBody
    public Map<String, Object> getRoleInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        String id;
        id = request.getParameter("roleId");
        SysRole role;
        role = new SysRole();
        try {
            role = this.sysRoleService.findEntityById(id);
            resultMap.put("resTree", this.sysResourceService.getResourceTree("3"));
        } catch (ServiceException | DaoException e) {
            e.printStackTrace();
        }
        resultMap.put("role", role);
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 查询角色下所有资源</p>
     * @param request 请求
     * @param roleId 角色ID
     * @return 资源列表
     */
    @RequestMapping(value = "/getRoleResource.mvc")
    @ResponseBody
    public Map<String, Object> getRoleResource (HttpServletRequest request, String roleId) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        List<String> resIds;
        resIds = new ArrayList<String>();
        try {
            resIds = this.sysRoleService.findResourceByRole(roleId);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        resultMap.put("resIds", resIds);
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 保存角色资源</p>
     * @param request 请求
     * @param roleId 角色ID
     * @return 操作结果
     */
    @RequestMapping(value = "/saveRoleResource.mvc")
    @ResponseBody
    public Map<String, Object> saveRoleResource (HttpServletRequest request, String roleId) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        String resIds = request.getParameter("resIds");
        String[] res = resIds.split(",");
        try {
            this.sysRoleService.saveRoleResource(roleId, res);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 角色新增/修改保存方法</p>
     * @param request 请求
     * @param role 角色
     * @return 结果
     */
    @RequestMapping(value = "/saveOrUpdateSysRole.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateSysRole(HttpServletRequest request, SysRole role) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        try {
            SysRole check;
            check = new SysRole();
            String sysuser = String.valueOf(request.getSession().getAttribute("sys.userName"));
            if (role.getPkId() != null && !"".equals(role.getPkId())) {
                //更新
                //查询更新后的角色是否与其他角色重复
                check = this.sysRoleService.findRoleExist(role);
                if (check != null) {
                    resultMap.put("msg", "repeat");
                    return resultMap;
                }
                //查询角色是否存在
                check = this.sysRoleService.findEntityById(role.getPkId());
                if (check == null) {
                    resultMap.put("msg", "error");
                    return resultMap;
                }
                check.setRname(role.getRname());
                check.setRdesc(role.getRdesc());
                check.setIsLock(role.getIsLock());
                check.setDelFlag("0");
                check.setUpdateDate(new Date());
                check.setHomePage(role.getHomePage());
                check.setUpdateUser(sysuser);
                resultMap.put("msg", this.sysRoleService.updateRecord(check));
            } else {
                //新增
                //验证是否与已有角色重复
                check = this.sysRoleService.findRoleExist(role);
                if (check != null) {
                    resultMap.put("msg", "repeat");
                    return resultMap;
                }
                role.setPkId(UUIDUtils.getUUID());
                role.setDelFlag("0");
                role.setCreateDate(new Date());
                role.setCreateUser(sysuser);
                role.setUpdateDate(new Date());
                role.setUpdateUser(sysuser);
                resultMap.put("msg", this.sysRoleService.insertRecord(role));
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 角色删除方法</p>
     * @param request 请求
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "/delSysRole.mvc")
    @ResponseBody
    public Map<String, Object> delSysRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        String ids;
        ids = request.getParameter("roleIds");
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("roleId", ids);
        map.put("updateUser", String.valueOf(request.getSession().getAttribute("sys.userName")));
        map.put("updateDate", new Date());
        try {
            this.sysRoleService.delRole(map);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 角色锁定</p>
     * @param request 请求
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "/lockSysRole.mvc")
    @ResponseBody
    public Map<String, Object> lockSysRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        String ids;
        ids = request.getParameter("roleIds");
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("roleId", ids);
        map.put("user", String.valueOf(request.getSession().getAttribute("sys.userName")));
        map.put("date", new Date());
        try {
            this.sysRoleService.lockRole(map);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
    /**
     * 
     * <p>Description: 删除角色下指定用户</p>
     * @param request 请求
     * @param response 响应
     */
    @RequestMapping(value = "/delUserFromRole.mvc")
    @ResponseBody
    public void delUserFromRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("roleId", request.getParameter("roleId"));
        map.put("userIds", request.getParameter("userIds").split(","));
        try {
            this.sysRoleService.deleteUserFromRole(map);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>Description: 为指定角色添加用户</p>
     * @param request 请求
     * @param response 响应
     */
    @RequestMapping(value = "/addUsersToRole.mvc")
    @ResponseBody
    public void addUsersToRole(HttpServletRequest request, HttpServletResponse response) {
        String roleId;
        roleId = request.getParameter("roleId");
        String[] userIds;
        userIds = request.getParameter("userIds").split(",");
        SysUserRole userRole;
        List<SysUserRole> list;
        list = new ArrayList<SysUserRole>();
        for (String id : userIds) {
        	//跳出循环
        	if(id.equals("test1")){
        		continue;
        	}
            userRole = new SysUserRole();
            userRole.setPkId(UUIDUtils.getUUID());
            userRole.setRoleId(roleId);
            userRole.setUserId(id);
            list.add(userRole);
        }
        try {
            this.sysRoleService.addUsersToRole(list);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
}
